import fiveVertSprite from "./fiveVertSprite";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    helloWorld: cc.Node = null;

    bounceSpeed: number = 500;

    onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
    }
    touchTween: cc.Tween = null;
    touchMove(touch) {
        if (this.touchTween) {
            this.touchTween.stop();
        }
        let sp = this.helloWorld.getComponent(fiveVertSprite);
        if (sp) {
            sp.anchorPoint = this.helloWorld.convertToNodeSpaceAR(touch.getLocation());
        }
    }
    // 每次反弹后
    bounceRate: number = 0.6;

    touchEnd(touch) {
        let sp = this.helloWorld.getComponent(fiveVertSprite);
        // let curPos = sp.anchorPoint;
        this.bounce(sp)
    }
    // 反弹
    bounce(sprite: fiveVertSprite) {
        let curPos = sprite.anchorPoint;
        if (curPos instanceof cc.Vec2) {
            let nextPos = curPos.mul(-this.bounceRate);
            if (nextPos.mag() < 5) {
                nextPos = cc.v2();
            }
            let dist = nextPos.mag();
            let time = dist / (this.bounceSpeed * dist * 0.025);
            this.touchTween = cc.tween(sprite)
                .to(time, { anchorPoint: nextPos })
                .call(() => {
                    if (nextPos.mag() != 0) {
                        this.bounce(sprite);
                    }
                })
                .start()
        }
    }

    update(dt) {

    }
}
